package com.axcbd.demo.controller;

import com.axcbd.demo.model.Camera;
import com.axcbd.demo.repository.CameraRepository;
import com.axcbd.demo.request.CameraRequest;
import com.axcbd.demo.service.CameraInformationService;
import com.axcbd.demo.service.CameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

@RestController
public class VideoStreamController {

    @Autowired
    private CameraRepository cameraRepo;

    @Autowired
    private CameraInformationService cameraInformationService;

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private Process pythonProcess;
    private final AtomicLong lastSaveTime = new AtomicLong(0); // 初始化为0，表示尚未保存过

    @GetMapping("/start-video-processing")
    public String startVideoProcessing(@RequestBody CameraRequest cameraRequest) {
        int cameraid = cameraRequest.getCameraid();
        System.out.println("start-video-processing endpoint called with camera: " + cameraid);

        if (isRunning.get()) {
            return "Video processing is already running";
        }

        // 通过cameraid从数据库获取Camera对象
        Camera camera = cameraRepo.findByCameraid(cameraid);
        if (camera == null) {
            return "Camera not found with ID: " + cameraid;
        }
        String rtspUrl = camera.getRtspurl();

        executorService.submit(() -> {
            try {
                String scriptPath = new File(this.getClass().getClassLoader().getResource("scripts/rtsp_move_rec_mjpeg_improve.py").toURI()).getAbsolutePath();
                System.out.println("Script path: " + scriptPath);

                // 构建命令行参数，包括RTSP URL
                ProcessBuilder processBuilder = new ProcessBuilder(
                        "python", scriptPath, camera.getRtspurl()
                );
                processBuilder.redirectErrorStream(true);

                pythonProcess = processBuilder.start();
                isRunning.set(true);

                Thread.sleep(1000);

                BufferedReader reader = new BufferedReader(new InputStreamReader(pythonProcess.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("Script output: " + line);
                    parseAndSaveCameraInfo(line, cameraid); // 新增：解析并保存截图信息
                }

                int exitCode = pythonProcess.waitFor();
                System.out.println("Process exited with code: " + exitCode);
                isRunning.set(false);

            } catch (Exception e) {
                e.printStackTrace();
                isRunning.set(false);
            }
        });

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return isRunning.get() ? "Video processing started" : "Failed to start video processing";
    }

    // 新增：解析Python脚本输出并保存到数据库
    private void parseAndSaveCameraInfo(String outputLine, int cameraid) {
        // 如果输出以特定模式开始，则认为是运动检测到的截图信息
        if (outputLine.startsWith("Motion Detected! Frame saved to")) {
            // 当前时间
            long currentTime = System.currentTimeMillis();
            // 检查是否已经保存过信息，并且距离上次保存的时间是否超过了阈值（例如10秒）
            if (lastSaveTime.get() == 0 || currentTime - lastSaveTime.get() >= 9000) { // 10000毫秒=10秒
                // 提取绝对路径
                String absolutePath = outputLine.substring(outputLine.indexOf("to ") + 3);
                // 保存到数据库
                cameraInformationService.saveCameraInformation(cameraid, absolutePath);
                // 更新最后保存的时间
                lastSaveTime.set(currentTime);
            } else {
                System.out.println("Duplicate motion detected within 9 seconds. Skipping save.");
            }
        }
    }

    // 注册关闭钩子
    {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("Shutdown hook triggered. Stopping Python process...");
            if (pythonProcess != null) {
                pythonProcess.destroy();
                try {
                    if (!pythonProcess.waitFor(5, TimeUnit.SECONDS)) {
                        pythonProcess.destroyForcibly();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            executorService.shutdownNow();
            System.out.println("Python process stopped.");
        }));
    }
}